import { toast, Toaster } from 'sonner';
import { useSettingsStore, Status, EditorButton, PersistenMode } from '@/store';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { cn, getCurrentTab } from '@/lib/utils';
import { CheckedState } from '@radix-ui/react-checkbox';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
type Key = 'ctrl' | 'alt' | 'shift';
function EditorModeSettings({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
  const dispatch = useSettingsStore((state) => state.dispatch);
  const editorSettings = useSettingsStore((state) => state.editorSettings);

  function keyChanged(checked: CheckedState, key: Key) {
    dispatch({
      type: 'update',
      editorSettings: {
        ...editorSettings,
        [key]: checked,
      },
    });
  }

  function mouseChanged(value: EditorButton) {
    dispatch({
      type: 'update',
      editorSettings: {
        ...editorSettings,
        button: value,
      },
    });
  }

  return (
    <div className={cn(className)} {...props}>
      <div className="mb-2">编辑模式配置:</div>
      <div className="inline-flex align-middle space-x-2 ml-3">
        <div>键盘:</div>
        <Checkbox
          onCheckedChange={(checked) => {
            keyChanged(checked, 'ctrl');
          }}
          checked={editorSettings.ctrl}
          className="rounded-[3px]"
          id="ctrl"
        />
        <label
          htmlFor="ctrl"
          className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
        >
          ctrl
        </label>
      </div>
      <div className="inline-flex align-middle space-x-2 ml-3">
        <Checkbox
          onCheckedChange={(checked) => {
            keyChanged(checked, 'alt');
          }}
          checked={editorSettings.alt}
          className="rounded-[3px]"
          id="alt"
        />
        <label
          htmlFor="alt"
          className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
        >
          alt
        </label>
      </div>
      <div className="inline-flex align-middle space-x-2 ml-3">
        <Checkbox
          onCheckedChange={(checked) => {
            keyChanged(checked, 'shift');
          }}
          checked={editorSettings.shift}
          className="rounded-[3px]"
          id="shift"
        />
        <label
          htmlFor="shift"
          className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
        >
          shift
        </label>
      </div>
      <RadioGroup
        value={editorSettings.button}
        className="flex ml-3 mt-2"
        onValueChange={mouseChanged}
      >
        <div>鼠标:</div>
        <div className="flex items-center space-x-2">
          <RadioGroupItem value={EditorButton.LEFT} id="mouse-r1" />
          <Label htmlFor="mouse-r1">左键</Label>
        </div>
        <div className="flex items-center space-x-2">
          <RadioGroupItem value={EditorButton.RIGHT} id="mouse-r3" />
          <Label htmlFor="mouse-r3">右键</Label>
        </div>
      </RadioGroup>
    </div>
  );
}

function PersistentSettings({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
  const dispatch = useSettingsStore((state) => state.dispatch);
  const persistentSettings = useSettingsStore((state) => state.persistentSettings);

  function handerCheckedChange(checked: boolean) {
    dispatch({
      type: 'update',
      persistentSettings: {
        ...persistentSettings,
        needPersistent: checked,
      },
    });
  }

  function modeChanged(value: PersistenMode) {
    dispatch({
      type: 'update',
      persistentSettings: {
        ...persistentSettings,
        currentMode: value,
      },
    });
  }

  async function clear() {
    const currentTab = await getCurrentTab();
    if (currentTab && currentTab.id) {
      chrome.tabs.sendMessage(currentTab.id, 'clear', () => {
        toast.success('已清理', {
          position: 'bottom-right',
        });
      });
    }
  }

  return (
    <div className={cn(className)} {...props}>
      <div className="mb-2">持久化配置:</div>
      <div className="flex items-center space-x-2 ml-3">
        <Checkbox
          onCheckedChange={handerCheckedChange}
          checked={persistentSettings.needPersistent}
          className="rounded-[3px]"
          id="need-persistent"
        />
        <label
          htmlFor="need-persistent"
          className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
        >
          是否需要持久化修改内容
        </label>
      </div>
      <div className="ml-2">
        <RadioGroup
          value={persistentSettings.currentMode}
          className="ml-3 mt-3"
          onValueChange={modeChanged}
        >
          <div>
            <div className="flex items-center">
              <RadioGroupItem value={PersistenMode.FlickerFreeMode} id="flicker-free" />
              <Label className="ml-2" htmlFor="flicker-free">
                无闪烁模式
              </Label>
            </div>
            <div className="ml-6 [&_label]:mt-1">
              <label className="flex items-center">
                <span
                  title="从页面刷新开始计时,超过后不再进行替换操作"
                  className="text-sm whitespace-nowrap"
                >
                  替换超时(ms):
                </span>
                <Input
                  value={persistentSettings.flickerFree.duration}
                  type="number"
                  onChange={(event) => {
                    dispatch({
                      type: 'update',
                      persistentSettings: {
                        ...persistentSettings,
                        flickerFree: {
                          ...persistentSettings.flickerFree,
                          duration: +event.target.value,
                        },
                      },
                    });
                  }}
                  className="ml-2 w-auto"
                ></Input>
              </label>
            </div>
          </div>
          <div>
            <div className="flex items-center">
              <RadioGroupItem value={PersistenMode.RollPollingMode} id="roll-polling" />
              <Label className="ml-2" htmlFor="roll-polling">
                轮询模式
              </Label>
            </div>
            <div className="ml-6 [&_label]:mt-1">
              <label className="flex items-center">
                <span
                  title="从页面刷新开始计时,超过后不再进行替换操作"
                  className="text-sm whitespace-nowrap"
                >
                  轮询间隔(ms):
                </span>
                <Input
                  value={persistentSettings.rollPolling.interval}
                  type="number"
                  onChange={(event) => {
                    dispatch({
                      type: 'update',
                      persistentSettings: {
                        ...persistentSettings,
                        rollPolling: {
                          ...persistentSettings.rollPolling,
                          interval: +event.target.value,
                        },
                      },
                    });
                  }}
                  className="ml-2 w-auto"
                ></Input>
              </label>
              <label className="flex items-center">
                <span
                  title="从页面刷新开始计时,超过后不再进行替换操作"
                  className="text-sm whitespace-nowrap"
                >
                  替换超时(ms):
                </span>
                <Input
                  value={persistentSettings.rollPolling.duration}
                  type="number"
                  onChange={(event) => {
                    dispatch({
                      type: 'update',
                      persistentSettings: {
                        ...persistentSettings,
                        rollPolling: {
                          ...persistentSettings.rollPolling,
                          duration: +event.target.value,
                        },
                      },
                    });
                  }}
                  className="ml-2 w-auto"
                ></Input>
              </label>
            </div>
          </div>
          <div className="flex items-center space-x-2">
            <RadioGroupItem value={PersistenMode.GlobalMode} id="global" />
            <Label htmlFor="global">全局模式</Label>
          </div>
        </RadioGroup>
      </div>
      <div className="ml-5 flex mt-3">
        <Button onClick={clear} variant="destructive" className="px-3 py-1 ml-auto mr-3">
          清理缓存
        </Button>
      </div>
    </div>
  );
}

function Settings() {
  const dispatch = useSettingsStore((state) => state.dispatch);
  const status = useSettingsStore((state) => state.status);

  function running() {
    dispatch({
      type: 'update',
      status: Status.RUNNING,
    });
    toast.success('启动', {
      position: 'bottom-right',
    });
  }

  function stop() {
    dispatch({
      type: 'update',
      status: Status.STOP,
    });
    toast.success('暂停', {
      position: 'bottom-right',
    });
  }

  function onCheckedChange(checked: boolean | 'indeterminate') {
    if (checked) {
      running();
    } else {
      stop();
    }
  }
  return (
    <>
      <div className="flex items-center space-x-2">
        <Switch
          checked={status === Status.RUNNING}
          onCheckedChange={onCheckedChange}
          id="airplane-mode"
        />
        <Label htmlFor="airplane-mode">
          <span className={`${status === Status.RUNNING ? 'text-[--primary]' : ''}`}>启动</span>/
          <span className={`${status === Status.STOP ? 'text-[red]' : ''}`}>暂停</span>
        </Label>
      </div>
    </>
  );
}

export function ExtensionSettings(props: React.ButtonHTMLAttributes<HTMLDivElement>) {
  return (
    <div {...props}>
      <div className="flex flex-col min-h-[200px]">
        <div className="flex-1">
          <Settings></Settings>
          <PersistentSettings className="mt-3"></PersistentSettings>
          <EditorModeSettings className="mt-3"></EditorModeSettings>
        </div>
        <Toaster duration={2000} className="max-w-[150px] !left-auto !right-0"></Toaster>
      </div>
    </div>
  );
}
